﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using XMK.Tadong.Biz;
using HU8.Helpers.Base;
using XMK.Tadong.Web.Language;

namespace XMK.Tadong.Web.DataAssetsStatistics
{
    public partial class AssetsStatistics : FileExplorerPage
    {
        public string firstId = "";
        protected void Page_Load(object sender, EventArgs e)
        {

            #region showSearchValue.htm 和 showSearchFile.htm 页面请求处理区域
            
            bool isQueryStructuredData = !string.IsNullOrEmpty(Request.QueryString["table"]);
            bool isQueryNonStructuredData = !string.IsNullOrEmpty(Request.QueryString["file"]);
            bool isQueryTableList = !string.IsNullOrEmpty(Request.QueryString["tableList"]);
            bool isIllegalQuery = !string.IsNullOrEmpty(Request.QueryString["page"]);
            if (isIllegalQuery) return;

            TB_Tree_ObjectBiz biz = new TB_Tree_ObjectBiz();
            DataTable dtRes = null;
            if (isQueryTableList)
            { //HttpUtil.
               // Server.UrlDecode
                string target = Request.Form["target"];//Server.UrlDecode(  Request.QueryString["target"].ToString());
                string bus = Request.Form["bus"];//Server.UrlDecode(Request.QueryString["bus"].ToString());
                dtRes = biz.getSearchTarget(target, bus);
                Response.Write(JsonHelper.ToJson(dtRes));
                Response.End();
                return; 
            }
            else if (isQueryStructuredData)
            {
                string tableName = Request.QueryString["table"].ToString();
                string target1 = HttpUtility.UrlDecode( Request.QueryString["target"].ToString());
                dtRes = biz.getTableData(tableName, target1);
                Response.Write(string.Concat("{\"total\":", dtRes.Rows.Count.ToString(), ", \"rows\":", JsonHelper.ToJson(dtRes), "}"));
                Response.End();
                return; 
            }
            else if (isQueryNonStructuredData)
            {
                string target2 = HttpUtility.UrlDecode( Request.QueryString["target"].ToString());
                string bus2 = HttpUtility.UrlDecode( Request.QueryString["bus"].ToString());
                dtRes = biz.getSearchBiz(target2, bus2);
                Response.Write(string.Concat("{\"total\":", dtRes.Rows.Count.ToString(), ", \"rows\":", JsonHelper.ToJson(dtRes), "}"));
                Response.End();
                return;
            }

            #endregion 


            string nodeId = Request.QueryString["id"];
           
            bool isQueryGridData = !string.IsNullOrEmpty(nodeId);
            if (!isQueryGridData)
            {
                firstId = BindFirstLevel();
            }
            else
            {
                DataTable dt = genTreeGridData(nodeId);
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["id"].ToString() == nodeId)
                    {
                        dt.Rows.Remove(dr);
                        break;
                    }
                }
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["_parentId"].ToString() == nodeId)
                    {
                        dr["_parentId"] = "";
                    }
                }
                dt.AcceptChanges();
                
                List<string> multiCol = new List<string>();
                Dictionary<string, string> dicCol = new Dictionary<string, string>();
                foreach (DataColumn dc in dt.Columns)
                {
                    string colname = dc.ColumnName;
                    if (colname.Contains(' '))
                    {
                        multiCol.Add(colname);
                        string[] names = colname.Split(' ');
                        foreach (string name in names)
                        {
                            if (dt.Columns.Contains(name))
                            {
                                foreach (DataRow dr in dt.Rows)
                                {
                                    string sigValue = dr[name].ToString();
                                    string mutValue = dr[colname].ToString();
                                    if (sigValue.Contains('/') && mutValue.Contains('/'))
                                    {
                                        string[] sigs = sigValue.Split('/');
                                        string[] muts = mutValue.Split('/');
                                        dr[name] = sigs[0] + "/ " + (Convert.ToInt32(sigs[1].Trim()) + Convert.ToInt32(muts[1].Trim())).ToString();
                                    }
                                }
                            }
                            else
                            {
                                dicCol.Add(name, colname);
                                //DataColumn dcnew = dt.Columns.Add();
                                //dcnew.ColumnName = name;
                                //dcnew.DataType = dc.DataType;
                                //foreach (DataRow dr in dt.Rows)
                                //{
                                //    dr[name] = dr[colname];
                                //}
                            }
                        }
                     //   dt.Columns.Remove(colname);
                        dt.AcceptChanges();
                    }
                }
                foreach (KeyValuePair<string, string> kv in dicCol)
                {
                    DataColumn dcnew = dt.Columns.Add();
                    dcnew.ColumnName = kv.Key;
                    dcnew.DataType = dt.Columns[kv.Value].DataType;
                    foreach (DataRow dr in dt.Rows)
                    {
                        dr[kv.Key] = dr[kv.Value];
                    }
                    dt.AcceptChanges();
                }
                foreach (string columnname in multiCol)
                {
                    dt.Columns.Remove(columnname);
                }
                dt.AcceptChanges();


                for (int j = 0; j < 2; j++)
                {
                    List<DataRow> rows = new List<DataRow>();
                    foreach (DataRow dr in dt.Rows)
                    {
                        int i = 1;
                        for (i = 1; i < dt.Columns.Count; i++)
                        {
                            if (dr[i].ToString().Contains('/'))
                            {
                                if (dr[i].ToString() != "0  /  0")
                                {
                                    break;

                                }
                            }
                        }
                        if (i == dt.Columns.Count)
                        {
                            DataRow[] arrayDR = dt.Select("_parentId='" + dr["id"].ToString() + "'");
                            if (arrayDR.Count() == 0)
                            {
                                rows.Add(dr);

                            }
                        }
                    }
                    foreach (DataRow dr in rows)
                    {
                        dt.Rows.Remove(dr);
                    }
                    dt.AcceptChanges();

                }

                List<DataColumn> dcs = new List<DataColumn>();
                foreach (DataColumn dc in dt.Columns)
                {
                    string colName = dc.ColumnName;
                    if (colName == "_" || colName == "其他" || colName == "id" || colName == "_parentId")
                    {
                        continue;
                    }
                    string total = "";
                    foreach (DataRow dr in dt.Rows)
                    {
                        total += dr[dc.ColumnName].ToString();
                    }
                    total = total.Replace('0', ' ');
                    total = total.Replace('/', ' ');
                    if (total.Trim().Length == 0)
                    {
                        dcs.Add(dc);
                    }

                }
                foreach (DataColumn dc in dcs)
                {
                    dt.Columns.Remove(dc);
                }

                if (dt.Rows.Count == 0)
                {
                    DataRow dr = dt.NewRow();
                    dt.Rows.Add(dr);
                    dt.AcceptChanges();
                }
                if (lang.Get("Luanguage_sys") == "english")
                {
                    //if (dt.Columns.Contains("目标"))
                    //{
                    //    dt.Columns["目标"].ColumnName = lang.Get("Target");
                    //}
                    if (dt.Columns.Contains("其他"))
                    {
                        dt.Columns["其他"].ColumnName = lang.Get("Other");
                    }
                }
                Response.Write(  "{\"total\":"+ dt.Rows.Count.ToString()+",\"rows\":" +  JsonHelper.ToJson(dt) +" }");
                Response.End();
            }
        }


        public DataTable genTreeGridData(string id)
        {
            int num = 1;
            List<string> sqlList = new List<string>();
            string unionSql = "";
            TB_Tree_ObjectBiz biz = new TB_Tree_ObjectBiz();
           
            if (string.IsNullOrEmpty(id))
            {
                id = firstId;
            }
            DataTable dtTree = biz.GetAllSubTreeTarget(id);
            foreach (DataRow dr in dtTree.Rows)
            {
                string newSql = dr["SH_SQL"].ToString().ToUpper();
                string obj_id = dr["OBJ_ID"].ToString();
                if (!string.IsNullOrEmpty(newSql))
                {

                    int index = newSql.IndexOf("FROM");
                    newSql = newSql.Insert(index, " name,to_char(" + obj_id + ") parentId ");
                    unionSql += " union all (" + newSql + ") ";
                }
            }
           

            DataTable dtUnion = new DataTable();
            if (!string.IsNullOrEmpty(unionSql))
            {
                unionSql = "select * from (" + unionSql.Substring(10) + ")";
                dtUnion = biz.QuerySql(unionSql);
            }

            DataTable dtFileData = new DataTable();
            dtFileData = genFileData(id);
            dtFileData.Columns[0].ColumnName = "_";
            DataColumn dcId = new DataColumn();
            dcId.DataType = typeof(long);
            dcId.ColumnName = "id";
            dtFileData.Columns.Add(dcId);
            DataColumn dcParentId = new DataColumn();
            dcParentId.DataType = typeof(string);
            dcParentId.ColumnName = "_parentId";
            dtFileData.Columns.Add(dcParentId);
            dtFileData.AcceptChanges();
            for (int i = 0; i < dtFileData.Rows.Count; i++)
            {
                dtFileData.Rows[i]["id"] = DateTime.Now.Ticks + num++; 
            }
            DataTable dtFileDataCopyt = dtFileData.Copy();

            DataRow[] drsFirst = dtFileData.Select();


            foreach (DataRow dr in dtTree.Rows)
            {
                DataRow drNew = dtFileData.NewRow();
                drNew["id"] = Int64.Parse(dr["OBJ_ID"].ToString());
                drNew["_"] = dr["OBJ_NAME"].ToString();
                drNew["_parentId"] = dr["P_OBJ_ID"].ToString();

                foreach (DataColumn dc in dtFileData.Columns)
                {
                    if (dc.ColumnName != "_" && dc.ColumnName != "其他"&& dc.ColumnName!="id" && dc.ColumnName!="_parentId")
                    {
                        int struVal = 0;
                        int nonstruVal = 0;
                        DataTable structTableName = biz.getSearchTarget(drNew["_"].ToString(), dc.ColumnName);
                        foreach (DataRow drTable in structTableName.Rows)
                        {
                            DataTable tmp = biz.getTableData(drTable["t_eng_name"].ToString(), drNew["_"].ToString());
                            struVal += tmp.Rows.Count;
                        }
                        DataTable nonstru = biz.getSearchBiz(drNew["_"].ToString(), dc.ColumnName);
                        nonstruVal = nonstru.Rows.Count;
                        drNew[dc.ColumnName] = struVal.ToString() + "  /  " + nonstruVal.ToString();
                    }
                }

                dtFileData.Rows.Add(drNew);

                //string obj_name = dr["OBJ_NAME"].ToString();
                //DataRow[] drs = dtFileData.Select("目标 = '" + obj_name + "'");
                //if (drs.Count() > 0)
                //{
                //    drs[0]["id"] = Int64.Parse( dr["OBJ_ID"].ToString());
                //    drs[0]["_parentId"] =  dr["P_OBJ_ID"].ToString();
                //}
                //else
                //{
                //    DataRow drNew = dtFileData.NewRow();
                //    drNew["id"] = Int64.Parse(dr["OBJ_ID"].ToString());
                //    drNew["目标"] = dr["OBJ_NAME"].ToString();
                //    drNew["_parentId"] =dr["P_OBJ_ID"].ToString();
                   
                //    //foreach (DataColumn dc in dtFileData.Columns)
                //    //{
                //    //    if (dc.ColumnName != "目标" && dc.ColumnName != "其他")
                //    //    {
                //    //    }
                //    //}
                //    dtFileData.Rows.Add(drNew);
                //}
            }

            foreach (DataRow dr in dtUnion.Rows)
            {
                string obj_name = dr["name"].ToString();
                DataRow[] drs = dtFileDataCopyt.Select("_ = '" + obj_name + "'");
                if (drs.Count() > 0)
                {
                    drs[0]["id"] = DateTime.Now.Ticks + num++;
                    drs[0]["_parentId"] = dr["parentId"].ToString();

                    dtFileData.ImportRow(drs[0]);
                }
            }
            foreach (DataRow dr in drsFirst)
            {
                dtFileData.Rows.Remove(dr);
            }

            dtFileData.AcceptChanges();

            return dtFileData;
        }

        public DataTable genFileData(string id )
        {
            TB_Tree_ObjectBiz biz = new TB_Tree_ObjectBiz();
            DataTable dt = MergeColumnToFirst(biz.getGridData(id));
            DataTable bus = biz.getBizNames();

            for (int i = 0; i < bus.Rows.Count; i++)
            {
                string value = bus.Rows[i][0].ToString();
                if (dt.Columns.Count >= i + 1)
                {
                    dt.Columns[i + 1].ColumnName = value;
                }
            }
            DataTable dtBiz = biz.getBisData(id);

            List<DataRow> mutRows = new List<DataRow>();
            foreach (DataRow dr in dtBiz.Rows)
            {
                if (dr["DEST_OBJ"].ToString().Contains(' '))
                {
                    mutRows.Add(dr);
                }
            }
            foreach (DataRow dr in mutRows)
            {
                string dest_obj = dr["DEST_OBJ"].ToString();
                string biz_obj = dr["BIZ_OBJ"].ToString();
                string[] objs = dest_obj.Split(' ');
                foreach (string obj in objs)
                {
                    DataRow[] drs = dtBiz.Select("DEST_OBJ='" + objs + "' and BIZ_OBJ= '" + biz_obj + "'");
                    if (drs.Length > 0)
                    {
                        drs[0]["NUM"] = Convert.ToInt32(drs[0]["NUM"]) + Convert.ToInt32(dr["NUM"]);
                    }
                    else
                    {
                        DataRow drnew = dtBiz.NewRow();
                        drnew["DEST_OBJ"] = obj;
                        drnew["BIZ_OBJ"] = biz_obj;
                        drnew["NUM"] = dr["NUM"];
                        dtBiz.Rows.Add(drnew);
                    }
                }
                dtBiz.Rows.Remove(dr);
            }
            dtBiz.AcceptChanges();
            mutRows.Clear();

            foreach (DataRow dr in dtBiz.Rows)
            {
                if (dr["BIZ_OBJ"].ToString().Contains(' '))
                {
                    mutRows.Add(dr);
                }
            }
            foreach (DataRow dr in mutRows)
            {
                string dest_obj = dr["DEST_OBJ"].ToString();
                string biz_obj = dr["BIZ_OBJ"].ToString();
                string[] objs = biz_obj.Split(' ');
                foreach (string obj in objs)
                {
                    DataRow[] drs = dtBiz.Select("DEST_OBJ='" + dest_obj + "' and BIZ_OBJ= '" + obj + "'");
                    if (drs.Length > 0)
                    {
                        drs[0]["NUM"] = Convert.ToInt32(drs[0]["NUM"]) + Convert.ToInt32(dr["NUM"]);
                    }
                    else
                    {
                        DataRow drnew = dtBiz.NewRow();
                        drnew["DEST_OBJ"] = dest_obj;
                        drnew["BIZ_OBJ"] = obj;
                        drnew["NUM"] = dr["NUM"];
                        dtBiz.Rows.Add(drnew);
                    }
                }
                dtBiz.Rows.Remove(dr);
            }
            dtBiz.AcceptChanges();

            DataColumn dcTag = new DataColumn();
            dcTag.DataType = typeof(Int32);
            dcTag.DefaultValue = 0;
            dcTag.ColumnName = "TAG";
            dtBiz.Columns.Add(dcTag);

            string numVal = "0";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string target = dt.Rows[i][0].ToString();
                for (int j = 1; j < dt.Columns.Count; j++)
                {
                    string bizName = dt.Columns[j].ColumnName;

                    //DataRow[] drs = dtBiz.Select("((dest_obj like '" + target + "') or (dest_obj like '" + target + "%') or (dest_obj like '%" + target + "') or (dest_obj like '% " + target + " %') ) and ( (biz_obj like '" + bizName + "') or  (biz_obj like '%" + bizName + "') or  (biz_obj like '" + bizName + "%') or  (biz_obj like '% " + bizName + " %') )   ");
                    DataRow[] drs = dtBiz.Select(" dest_obj = '"+target+"' and biz_obj = '"+bizName +"' ");
                    numVal = "0";
                    if (drs.Length > 0)
                    {
                        numVal = drs[0]["NUM"].ToString();
                        drs[0]["TAG"] = "1";
                    }
                    dt.Rows[i][j] = dt.Rows[i][j].ToString() + "  /  " + numVal;
                }
            }
            DataRow[] drsLeft = dtBiz.Select("TAG='0'");
            Dictionary<string, List<DataRow>> biz_objs = new Dictionary<string, List<DataRow>>();
            foreach (DataRow dr in drsLeft)
            {
                string strBiz = dr["BIZ_OBJ"].ToString();
                if (string.IsNullOrEmpty(strBiz))
                {
                    strBiz = "其他";
                }
                if (!biz_objs.ContainsKey(strBiz))
                {
                    biz_objs.Add(strBiz, new List<DataRow>());//[strBiz].Add(dr);
                }
                biz_objs[strBiz].Add(dr);

            }
            List<DataRow> extRow = biz_objs.ContainsKey("其他") ? biz_objs["其他"] : null;
            biz_objs.Remove("其他");
            dt.Columns[0].ColumnName = "_";
            foreach (KeyValuePair<string, List<DataRow>> kv in biz_objs)
            {
                if (dt.Columns.Contains(kv.Key))
                {
                    continue;
                }

                DataColumn dc = new DataColumn();
                dc.ColumnName = kv.Key;
                dc.DataType = typeof(string);
                dc.DefaultValue = "0  /  0";
                dt.Columns.Add(dc);
                foreach (DataRow dr in kv.Value)
                {
                    DataRow[] drs = dt.Select("_ ='" + dr["DEST_OBJ"] + "'");
                    if (drs.Length > 0)
                        drs[0][kv.Key] = "0  /  " + dr["NUM"].ToString();
                }
             
            }
            if (extRow != null)
            {
                DataColumn dc = new DataColumn();
                dc.ColumnName = "其他";
                dc.DataType = typeof(string);
                dc.DefaultValue = "0  /  0";
                dt.Columns.Add(dc);
                foreach (DataRow dr in extRow)
                {
                    DataRow[] drs = dt.Select("_ ='" + dr["DEST_OBJ"] + "'");
                    if (drs.Length > 0)
                        drs[0]["其他"] = "0  /  " + dr["NUM"].ToString();
                }
            }
            return dt;
          
        }

        public string  BindFirstLevel()
        {
            string resultId="";
            TB_Tree_ObjectBiz biz = new TB_Tree_ObjectBiz();
            DataTable dtFirst = biz.GetSubTreeTarget("0");
            Repeater1.DataSource = dtFirst;
            Repeater1.DataBind();
            if (dtFirst.Rows.Count > 0)
            {
                resultId = dtFirst.Rows[0]["obj_id"].ToString();
            }
            return resultId;

        }

        public DataTable MergeColumnToFirst(DataTable dt)
        {

            int colNum = dt.Columns.Count;
            for (int j = 0; j < dt.Rows.Count;j++ )
            {

                for (int i = 2; i < colNum; i+=2 )
                {
                    if (!string.IsNullOrEmpty( dt.Rows[j][i].ToString()))
                    {
                        dt.Rows[j][0] = dt.Rows[j][i];
                    }
                }
            }

            DataTable result = dt;
            List<DataColumn> dcs= new List<DataColumn>();

            foreach (DataColumn dc in result.Columns)
            {
               if (dc.ColumnName.Contains("BUS"))
                {
                    dcs.Add(dc);
                     
                }
            }
            if(dcs.Count>0)
               dcs.RemoveAt(0);

            foreach (DataColumn dc in dcs)
            {
                result.Columns.Remove(dc);
            }

            for (int i = 0; i < result.Rows.Count; i++)
            {
                for (int j = 1; j < result.Columns.Count; j++)
                {
                    if (string.IsNullOrEmpty(result.Rows[i][j].ToString() ))
                    {
                        result.Rows[i][j] = "0";
                    }
                }
            }

            return result;
            
        }

    }
}